package com.csglxt.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 
 * @ClassName: HttpClient
 * @Description: http请求工具类
 * @author Delver_Si
 * @date 2015-5-28 下午11:56:46
 * 
 */

public class HttpClient {
    // 发送一个GET请求
    public static String get(String path) throws Exception {
        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        try {
            URL url = new URL(path);
            httpConn = (HttpURLConnection) url.openConnection();

            // 读取响应
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer content = new StringBuffer();
                String tempStr = "";
                in = new BufferedReader(new InputStreamReader(
                        httpConn.getInputStream()));
                while ((tempStr = in.readLine()) != null) {
                    content.append(tempStr);
                }
                return content.toString();
            } else {
                throw new Exception("请求出现了问题!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            in.close();
            httpConn.disconnect();
        }
        return null;
    }

    // 发送一个GET请求,参数形式key1=value1&key2=value2...
    public static String post(String path, String params) throws Exception {
        HttpURLConnection httpConn = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            URL url = new URL(path);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

            // 发送post请求参数
            out = new PrintWriter(httpConn.getOutputStream());
            out.println(params);
            out.flush();

            // 读取响应
            if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer content = new StringBuffer();
                String tempStr = "";
                in = new BufferedReader(new InputStreamReader(
                        httpConn.getInputStream()));
                while ((tempStr = in.readLine()) != null) {
                    content.append(tempStr);
                }
                return content.toString();
            } else {
                throw new Exception("请求出现了问题!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            in.close();
            out.close();
            httpConn.disconnect();
        }
        return null;
    }

    public static String getIp() throws Exception {
        String msg = HttpClient.get("http://city.ip138.com/ip2city.asp");
        int begin = msg.indexOf("[");
        int end = msg.indexOf("]");
        return msg.substring(begin + 1, end);
    }

    public static String getIpInfo(String ip) throws Exception {
        return HttpClient.get("http://freeapi.ipip.net/?ip=" + ip);
    }

    public static String getCityInfo(String city) throws Exception {
        return HttpClient
                .get("http://apistore.baidu.com/microservice/cityinfo?cityname="
                        + city);
    }

    public static String getWeatherTemp(String cityCode) throws Exception {
        return HttpClient
                .get("http://apistore.baidu.com/microservice/weather?cityid="
                        + cityCode);
    }

    /**
     * 
     * @param ip
     *            221.234.230.1
     * @return
     * @throws Exception
     */
    private static String getCityName(String ip) throws Exception {
        return (((Object[]) JsonUtil.getObjectArrayFromJson(getIpInfo(ip)))[2])
                .toString();
    }

    private static Object getCity(String cityName) throws Exception {
        String cityInfo_Json = getCityInfo(cityName);
        return JsonUtil.getMapFromJson(cityInfo_Json).get("retData");
    }

    private static String getCityCode(Object city) throws Exception {
        String city_Json = JsonUtil.getJSONString(city);
        Object cityCode = JsonUtil.getMapFromJson(city_Json).get("cityCode");
        return cityCode.toString();
    }

    private static String getWeather(String cityCode) throws Exception {
        String Weather_JsonTemp = getWeatherTemp(cityCode);
        Object weather = JsonUtil.getMapFromJson(Weather_JsonTemp).get(
                "retData");
        return weather.toString();
    }

    public static String getWeatherJson(String ip) throws Exception {

        return getWeather(getCityCode(getCity(getCityName(ip))));
    }
}